package com.swpu.project.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swpu.project.common.BaseResponse;
import com.swpu.project.mapper.MenuMapper;
import com.swpu.project.mapper.UserMapper;
import com.swpu.project.model.dto.user.UserLoginRequest;
import com.swpu.project.model.entity.User;
import com.swpu.project.model.page.PageDto;
import com.swpu.project.model.page.PageQuery;
import com.swpu.project.model.vo.UserVO;
import com.swpu.project.service.IUserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author swpuyanxiegroup1
 * @since 2024-07-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    UserMapper userMapper;
  @Resource
    MenuMapper menuMapper;
    @Override
    public BaseResponse queryUserInform(PageQuery pageQuery) {


        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        int start = (pageNum - 1) * pageSize;
        int end = pageSize;
        Map<String, String> queryBy = pageQuery.getQueryBy();

        Map<String, Boolean> sortBy = pageQuery.getSortBy();
        Long count = lambdaQuery().count();

        count/=pageSize;
        if (count==0)
            count=1L;
        List<UserVO> userVOS = userMapper.selectAndOrderUser(start, end, queryBy, sortBy);
        HashMap<Long, UserVO> userIdmap =(HashMap<Long, UserVO>)
                userVOS.stream().collect(Collectors.toMap(UserVO::getId, userVO -> userVO));
        List<Integer> userIds = userVOS.stream().map(userVO -> (userVO.getId().intValue())).collect(Collectors.toList());
           //TODO 通过自定义mysql将user对应的role集合赋值进去

        setRole(userIdmap,userIds);
        userVOS=userIdmap.values().stream().collect(Collectors.toList());
          setPage(userVOS,count.intValue());
        PageDto userVOPageDto = new PageDto();
        userVOPageDto.setTotal(userVOS.size());
        userVOPageDto.setPages(count.intValue());
        userVOPageDto.setData(userVOS);

        return BaseResponse.ok( setPage(userVOS,count.intValue()));
    }

    private PageDto setPage(List<UserVO> userVOS, int intValue) {
        PageDto userVOPageDto = new PageDto();
        userVOPageDto.setTotal(userVOS.size());
        userVOPageDto.setPages(intValue);
        userVOPageDto.setData(userVOS);
    return userVOPageDto;
    }

    private void setRole(HashMap<Long, UserVO> userIdmap, List<Integer> userIds)
    {
        List<HashMap<String, Object>> roleList = userMapper.selectBatchRoleForUser(userIds);
        for (HashMap<String, Object> map : roleList) {
            Long id = (Long)map.get("id");
            String name = (String) map.get("name");
             if(name ==null)
                 continue;
            UserVO userVO = userIdmap.get(id);
            userVO.setRoles(name);

        }


    }


    @Override
    public BaseResponse login(UserLoginRequest userLoginRequest) {
        return null;
    }

    @Override
    public BaseResponse saveMyUser(User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        user.setPassword(encode);


        return BaseResponse.iFSuccess(save(user));
    }

    /*@Override
    public BaseResponse login(UserLoginRequest userLoginRequest) {
        String account = userLoginRequest.getAccount();
        String password = userLoginRequest.getPassword();
        //检验验证码未实现
        User user = lambdaQuery().eq(User::getUserAccount, account).eq(User::getUserPassword, password).one();
        if (user == null)
       return   BaseResponse.fail("用户不存在");
        String token = UUID.randomUUID().toString();
        String key = RedisConstant.USER_TOKEN_PREFIX + token;
       UserDto userDto = BeanUtil.copyProperties(user,UserDto.class);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userDto,new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor
                ( (fieldName,fieldValue) -> fieldValue +""));
        stringRedisTemplate.opsForHash().putAll(key,stringObjectMap);
        stringRedisTemplate.expire(key,RedisConstant.TOKEN_EXPIRE_TIME, TimeUnit.MINUTES);
        System.out.println("helloworld");
        return BaseResponse.ok(token);


    }*/


    private Page setPage(PageQuery pageQuery) {
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        Page<User> page = Page.of(pageNum, pageSize);
        pageQuery.initSortBy(page);


        return page;

    }

}
